/*
 * #depends tree-loader.js
 */
Ext.ns('Ext.ux.mattgoldspink.subsonic');        
Ext.ux.mattgoldspink.subsonic.FolderTreePanel = Ext.extend(Ext.tree.TreePanel, {
    constructor: function(config){
        Ext.apply(this, config, {
            autoScroll: true,
            plugins: ['msgbus'],
            rootVisible: false,
            root: this.makeInitialRoot(),
            // Our custom TreeLoader:
            loader: new Ext.ux.mattgoldspink.subsonic.FolderLoader({}),
			enableDrop: true,
			ddGroup: 'grid2tree',
			ddScroll: true
        });
        Ext.ux.mattgoldspink.subsonic.FolderTreePanel.superclass.constructor.apply(this, arguments);
        this.setupListeners();
        this.setupSubscriptions();
    },
	initComponent: function(){
		Ext.ux.mattgoldspink.subsonic.FolderTreePanel.superclass.initComponent.apply(this);
		this.editor = new Ext.tree.TreeEditor(this);
		this.editor.on('beforestartedit', function(ed, boudnEl, value) {
			if (!ed.editNode.attributes.playlist) {
				return false;
			}
		});
		this.editor.on('complete', function(node, newValue, startValue) {
            if (!node.editNode.attributes.notYetCreated) {
			    this.publish('subsonic.playlist.renamed', {
			        id: node.editNode.id,
			        text: newValue
			    });
			}
		}, this);
	},
    setupSubscriptions: function(){
        this.subscribe('subsonic.folder.selected', {fn: this.handleFolderSelected, scope: this});
        this.subscribe('subsonic.login.ok', {fn: function(topic, data){
           this.getRootNode().item(0).reload();
        }, scope: this});
		this.subscribe('subsonic.playlist.created', {fn: this.handlePlaylistCreated, scope: this});
		this.subscribe('subsonic.playlist.created.success', {fn: this.handlePlaylistCreatedSuccess, scope: this});
		this.subscribe('subsonic.playlist.renamed.success', {fn: this.handlePlaylistCreatedSuccess, scope: this});
		this.subscribe('subsonic.playlist.updated.success', {fn: this.reloadPlaylist, scope: this});
    },
	reloadPlaylist: function(topic, data){
	
	},
	handlePlaylistCreatedSuccess: function(topic, data) {
	    var playlistNode = this.getNodeById('playlists');
	    playlistNode.reload();
	},
	handlePlaylistCreated: function(topic, data) {
		var playlistNode = this.getNodeById('playlists');
		playlistNode.expand(false, true, function() {
			var newNode = playlistNode.appendChild({
				name: 'untitled playlist',
				notYetCreated: true
			});
			newNode.select();
			this.editor.triggerEdit(newNode);
		}, this);
	},
    handleFolderSelected: function(topic, data){
        var node = this.getNodeById(data.id);
        if (Ext.isEmpty(node)){
            node = this.getSelectionModel().getSelectedNode();
            if (!Ext.isEmpty(node) && node.hasChildNodes()){
                this.getSelectionModel().getSelectedNode().expand(false, false, function(){
                    this.publish('subsonic.folder.selected', {id: data.id});
                }, this);
            }
        } else {
            node.expand();
            node.select();
        }
    },
    makeInitialRoot: function(){
        return {
            id: 'rootNode',
            nodeType: 'async',
            children: [
                {
                    text: 'Library',
                    id: 'library',
                    cls: 'library-node'    ,
                    expanded: true,
                    expandable: false,
                    nodeType: 'async',
                    nextUrl: Ext.ux.mattgoldspink.subsonic.apiUrl + '/rest/getMusicFolders.view',
                    nextRoot: 'musicFolders.musicFolder'
                },
                {
                    text: 'Playlists',
                    id: 'playlists',
                    cls: 'playlist-node',    
                    nodeType: 'async',
                    nextUrl: Ext.ux.mattgoldspink.subsonic.apiUrl + '/rest/getPlaylists.view',
                    nextRoot: 'playlists.playlist'
                 }
             ]
        };
    },
    setupListeners: function() {
        this.on('click', this.handleClick, this);
		this.on('beforenodedrop', this.handleBeforeNodeDrop, this);
		this.on('nodedragover', this.handleNodeDragOver, this);
    },
	handleBeforeNodeDrop: function(e) {
		e.cancel = false;
		var data = {songs: e.data.selections};
		data.name = e.target.text;
		if (!e.target.attributes.notYetCreated) {
			data.playlistId = e.target.id;
		}
		this.publish('subsonic.playlist.track.added', data);
		return true;
	},
	handleNodeDragOver: function(e) {
		if (!e.target.attributes.playlist) {
			e.cancel = true;
		}
	},
    handleClick: function(node, event) {
        if (Ext.isDefined(node.attributes.subject)){
			if (!node.attributes.notYetCreated){
				this.publish(node.attributes.subject, node.attributes);
			}
        } else {
            node.expand();
        }
    }
});
